package com.ruoyi.web.controller.TiebaChatUser.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.controller.TiebaChatUser.domain.TiebaChatUser;
import com.ruoyi.web.controller.TiebaChatUser.mapper.TiebaChatUserMapper;
import com.ruoyi.web.controller.TiebaChatUser.service.ITiebaChatUserService;
import com.ruoyi.web.controller.TiebaChatUser.vo.TiebaChatUserAddReq;
import com.ruoyi.web.controller.TiebaChatUser.vo.TiebaChatUserReq;
import com.ruoyi.web.controller.TiebaChatUser.vo.TiebaChatUserResp;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 聊天对象Controller
 *
 * @author yong
 * @date 2025-03-09
 */
@Api(tags = "用户-聊天对象")
@RestController
@RequestMapping("/TiebaChatUser/TiebaChatUser")
public class TiebaChatUserController extends BaseController {
    @Autowired
    private ITiebaChatUserService tiebaChatUserService;

    @Resource
    private TiebaChatUserMapper tiebaChatUserMapper;
    @Resource
    private SysUserMapper sysUserMapper;


    /**
     * 查询聊天对象列表
     */
    @ApiOperation("聊天对象列表--分页")
//    @PreAuthorize("@ss.hasPermi('TiebaChatUser:TiebaChatUser:list')")
    @GetMapping("/list")
    public TableDataInfo list() {
        startPage();
        Long currentUserId = getUserId();
        TiebaChatUser tiebaChatUser = new TiebaChatUser();
        tiebaChatUser.setUserId(currentUserId);
        List<TiebaChatUser> userList = tiebaChatUserService.selectTiebaChatUserList(tiebaChatUser);

        if (userList.isEmpty()) {
            // 如果没有聊天用户，获取所有用户数据
            List<SysUser> allUsers = sysUserMapper.getAllUsers();
            // 检查这些用户是否已经存在于聊天用户表中
            List<Long> existingChatUserIds = tiebaChatUserService.selectUserIdsByCondition(tiebaChatUser);
            List<SysUser> newUsers = allUsers.stream()
                    .filter(user -> !existingChatUserIds.contains(user.getUserId()) && !user.getUserId().equals(currentUserId))
                    .collect(Collectors.toList());
            // 将这些用户添加到聊天用户表中
            List<TiebaChatUser> newChatUsers = newUsers.stream()
                    .map(user -> new TiebaChatUser(currentUserId, user.getUserId(), getDeptId(), user.getAvatar(), user.getUserName()))
                    .collect(Collectors.toList());
            tiebaChatUserService.saveBatch(newChatUsers);
            // 重新获取聊天用户列表
            userList = tiebaChatUserService.selectTiebaChatUserList(tiebaChatUser);
        }

        // 用户头像
        List<TiebaChatUserResp> userResps = new ArrayList<>();
        for (TiebaChatUser user : userList) {
            // 用户信息
            SysUser sysUser = sysUserMapper.selectUserById(user.getChatUserId());
            TiebaChatUserResp userResp = new TiebaChatUserResp();
            userResp.setId(user.getId());
            userResp.setAvatarUrl(sysUser.getAvatar());
            userResp.setChatUserId(user.getChatUserId());
            userResp.setLastMessage(user.getLastMessage());
            userResp.setUsername(sysUser.getUserName());
            userResp.setLastMessageTime(user.getLastMessageTime());
            userResps.add(userResp);
        }
        // 用户响应速度
        return getDataTable(userResps);
    }


    /**
     * 新增聊天对象
     */
    @ApiOperation("新增聊天对象")
    @PreAuthorize("@ss.hasPermi('TiebaChatUser:TiebaChatUser:add')")
    @Log(title = "聊天对象", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TiebaChatUserAddReq userAddReq) {

        TiebaChatUser tiebaChatUser = new TiebaChatUser();
        tiebaChatUser.setUserId(getUserId());
        tiebaChatUser.setDeptId(getDeptId());
        tiebaChatUser.setAvatarUrl(userAddReq.getAvatarUrl());
        tiebaChatUser.setChatUserId(userAddReq.getChatUserId());
        tiebaChatUser.setUsername(userAddReq.getUsername());
        // 检测用户是否存在
        LambdaQueryWrapper<TiebaChatUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(TiebaChatUser::getUsername, userAddReq.getUsername());
        TiebaChatUser chatUser = tiebaChatUserMapper.selectOne(userLambdaQueryWrapper);
        if (chatUser != null) {
            return AjaxResult.success("用户已经存在", chatUser);
        }
        return toAjax(tiebaChatUserService.save(tiebaChatUser));
    }


    /**
     * 删除聊天对象
     */
    @ApiOperation("删除聊天对象")
    @PreAuthorize("@ss.hasPermi('TiebaChatUser:TiebaChatUser:remove')")
    @Log(title = "聊天对象", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tiebaChatUserService.removeByIds(Arrays.asList(ids)));
    }
}
